package com.yunfei.api.smrz;
import com.yunfei.api.smrz.bo.AppFileBo;
import com.yunfei.api.smrz.bo.AppFileSimpleBo;
import com.yunfei.api.smrz.bo.ShenHeYiJianBo;
import com.yunfei.bo.city.CityBo;
import com.yunfei.bo.city.ProvinceBo;
import com.yunfei.bo.crmAcceDtl.CrmAcceDtlBo;
import com.yunfei.bo.result.ResultModel;
import com.yunfei.bo.smrz.IdCardBo;
import com.yunfei.bo.smrz.IdCardType;
import com.yunfei.bo.smrz.SmrzBo;
import com.yunfei.bo.smrz.XuLieHaoBao;
import com.yunfei.entity.TPersonalUserEntity;
import com.yunfei.entity.TblobstorageEntity;
import com.yunfei.entity.crmAcceDtl.CrmAcceDtlEntity;
import com.yunfei.enums.ResultStatus;
import com.yunfei.enums.ShiMingRenZhengStatus;
import com.yunfei.mapper.aiiidb.*;
import com.yunfei.mapper.crm.ShiMingRenZhengFileMapper;
import com.yunfei.mapper.crm.TblobtSorageMapper;
import com.yunfei.service.ShiMingRenZhengService;
import com.yunfei.utils.idcard.SmrzUtils;
import com.yunfei.utils.json.JsonListUtil;
import com.yunfei.utils.procedure.ShiMingRenZhengProcedure;
import com.yunfei.utils.procedure.ShiMingRenZhengProcedureReturnInfo;
import com.yunfei.utils.string.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.rmi.transport.ObjectTable;

import javax.servlet.http.HttpServletRequest;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @Description: 实名认证接口-理财师
 * @Author: zhengyunfei
 * @Date: 2018/6/15
 * @time:11:26
 */
@SuppressWarnings("ALL")
@Api(value = "实名认证",tags = "实名认证(理财师发起)")
@RestController
@RequestMapping("/api/licashi/smrz")
public class ShiMingRenZhengApiController {
    @Autowired
    private ShiMingRenZhengUploadMapper shiMingRenZhengUploadMapper;

    @Autowired
    private ShiMingRenZhengMapper shiMingRenZhengMapper;
    @Autowired
    private Environment env;
    @Autowired
    private TblobtSorageMapper tblobtSorageMapper;
    @Autowired
    private ShiMingRenZhengFileMapper shiMingRenZhengFileMapper;
    @Autowired
    private ShiMingRenZhengService shiMingRenZhengService;
    @Autowired
    private ShenHeYiJianMapper shenHeYiJianMapper;
    @Autowired
    private TPersonalUserMapper tPersonalUserMapper;
    @Autowired
    private CrmAcceDtlMapper crmAcceDtlMapper;
    /**
    * @Description: 获取所有证件类型
    * @Author: zhengyunfei
    * @Date: 2019/1/11
    * @time:17:00
    */
    @GetMapping("/get")
    @ApiOperation(value = "获取所有证件类型",notes = "获取所有证件类型",position = 1,response = Object.class)
    public Object getAllCardType(String cCustNo){
        ResultModel resultModel=new ResultModel();
        Map<String,Object> resultMap=new HashMap<>();
        List<IdCardType> idCardTypeList=shiMingRenZhengMapper.getCardType(null);
        List<ProvinceBo> provinceList=shiMingRenZhengMapper.getProvince(null);
        for(int i=0;i<provinceList.size();i++){
            String value=provinceList.get(i).getValue();
            Map<String,Object> queryMap=new HashMap<>();
            queryMap.put("value",value);
            List<CityBo> cityList=shiMingRenZhengMapper.getCity(queryMap);
            provinceList.get(i).setChildren(cityList);
        }
        Map<String,Object> queryMap=new HashMap<>();
        queryMap.put("cCustNo",cCustNo);
        IdCardBo cardBo= shiMingRenZhengMapper.getLookInfo(queryMap);
        if(StringUtil.isNullOrEmpty(cardBo)){
            //如果是客户身份的话，传递过来的cCustNo是userId
            TPersonalUserEntity tp=tPersonalUserMapper.findById(cCustNo);
            if(!StringUtil.isNullOrEmpty(tp)) {
                cardBo = new IdCardBo();
                cardBo.setMobile(tp.getMobile());
                cardBo.setUserName(tp.getUserName());
            }
        }
        resultMap.put("userInfo",cardBo);
        resultMap.put("cityData",provinceList);
        resultMap.put("cardType",idCardTypeList);

        resultModel.setCode(ResultStatus.SUCCESS.getCode());
        resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
        resultModel.setData(resultMap);
        return resultModel;
    }
    /**
     * @Description: 根据手机号码判断手机号是否在crm已经实名认证
     * 如果手机号在crm对应的客户已经进行了实名认证，无需实名认证
     * 判断手机号是否在crm已经实名认证：
     * 如果下面的sql结果大于0，已实名认证，无需进行实名认证
     * @Author: zhengyunfei
     * @Date: 2019/1/11
     * @time:17:00
     */
    @PostMapping(value = "/save",produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "实名认证",notes = "实名认证(理财师发起)",position = 1,response = Object.class)
    public Object save(IdCardBo idCardBo, HttpServletRequest request){
        ResultModel resultModel=new ResultModel();
        Map<String,Object> queryMap=new HashMap<>();
        System.out.println("实名认证email==========================="+idCardBo.getEmail());
        //参数格式校验
        String userName=idCardBo.getUserName();
        String cardType=idCardBo.getCardType();//证件类型
        String cardNo=idCardBo.getCardNo();//证件号码
        String cCustNo=idCardBo.getcCustNo();
        String mobile=idCardBo.getMobile();
        if (shiMingRenZhengService.validParamMethod(resultModel,idCardBo)) return resultModel;
        String validCode=resultModel.getCode()+"";
        //校验附件
        if(!"0".equals(cardType)){//不是身份证校验附件必填
            String imgLength=idCardBo.getImgLength();
            if(!StringUtil.isNullOrEmpty(imgLength)){
                int count=Integer.parseInt(imgLength);
                if(count==0){
                    resultModel.setMessage(ShiMingRenZhengStatus.CARD_PIC_ERROR.getMessage());
                    resultModel.setCode(ShiMingRenZhengStatus.CARD_PIC_ERROR.getCode());
                    return resultModel;
                }
            }else{
                resultModel.setMessage(ShiMingRenZhengStatus.CARD_PIC_ERROR.getMessage());
                resultModel.setCode(ShiMingRenZhengStatus.CARD_PIC_ERROR.getCode());
                return resultModel;
            }
        }
        //根据客户编号查询手机号码,前台获取手机号码
        if(StringUtil.isNullOrEmpty(mobile)){
            Map<String,Object> paramMap=new HashMap<>();
            paramMap.put("cCustNo",cCustNo);
            String mobileValue=shiMingRenZhengMapper.getMobileByCustNo(paramMap);
            idCardBo.setMobile(mobileValue);
        }
        Connection con = shiMingRenZhengService.getConnection();
        ShiMingRenZhengProcedure shiMingRenZhengProcedure=new ShiMingRenZhengProcedure();
        ShiMingRenZhengProcedureReturnInfo returnInfo=shiMingRenZhengProcedure.save(idCardBo,con);
        String reasonCode=returnInfo.getpReasonCode();
        if("1".equals(reasonCode)){
            resultModel.setCode(ResultStatus.SUCCESS.getCode());
            resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
            resultModel.setData(returnInfo.getpReasonCode2());//返回实名认证对应附件输出编号
        }else{
            resultModel.setCode(ResultStatus.ERROR.getCode());
            resultModel.setMessage(returnInfo.getpReasonInfo());
            return resultModel;
        }
        //如果是身份证 校验身份证和姓名是否匹配
        if("0".equals(cardType)){
            SmrzBo result= SmrzUtils.getResult(userName,cardNo);
            if(!result.getStatus().equals("01")){
                // resultModel.setMessage("姓名和身份证号不匹配");
                resultModel.setMessage(returnInfo.getpReasonInfo());
                resultModel.setCode(ShiMingRenZhengStatus.SHI_MING_REN_ZHENG_STATUS_ERROR.getCode());
                return resultModel;
            }else{
                //实名认证成功，同时更新实名认证的状态
                shiMingRenZhengService.updateSmrzStatus(resultModel, cCustNo,userName);
            }
        }
        return resultModel;
    }

    /***查看**/
   @GetMapping("/edite")
   @ApiOperation(value = "查看",notes = "查看",position = 1,response = Object.class)
   public Object edite(String cCustNo){
       ResultModel resultModel=new ResultModel();
       Map<String,Object> resultMap=new HashMap<>();
       Map<String,Object> queryMap=new HashMap<>();
       queryMap.put("cCustNo",cCustNo);
       IdCardBo cardBo= shiMingRenZhengMapper.getLookInfo(queryMap);
       List<AppFileSimpleBo> fileList=shiMingRenZhengMapper.getSmrzFile(queryMap);
       resultMap.put("resultInfo",cardBo);
       resultMap.put("resultFile",fileList);
       //获取审核意见
       Map<String,Object> shenHeQueryMap=new HashMap<>();
       List<ShenHeYiJianBo> shenHeYiJianBoList=new ArrayList<>();
       XuLieHaoBao xuLieHaoBao= (XuLieHaoBao) shiMingRenZhengMapper.getPserilNo(queryMap);//序列号
       if(!StringUtil.isNullOrEmpty(xuLieHaoBao)){
           String pSerilNo=xuLieHaoBao.getlSerialNo();
           shenHeQueryMap.put("lSerialno",pSerilNo);
           shenHeYiJianBoList=shenHeYiJianMapper.smrzShenHeYiJianList(shenHeQueryMap);
       }
       resultMap.put("shenHeYiJian",shenHeYiJianBoList);


       List<IdCardType> idCardTypeList=shiMingRenZhengMapper.getCardType(null);
       List<ProvinceBo> provinceList=shiMingRenZhengMapper.getProvince(null);
       for(int i=0;i<provinceList.size();i++){
           String value=provinceList.get(i).getValue();
           Map<String,Object> cityMap=new HashMap<>();
           cityMap.put("value",value);
           List<CityBo> cityList=shiMingRenZhengMapper.getCity(cityMap);
           provinceList.get(i).setChildren(cityList);
       }
       resultMap.put("cityData",provinceList);
       resultMap.put("cardType",idCardTypeList);

       resultModel.setCode(ResultStatus.SUCCESS.getCode());
       resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
       resultModel.setData(resultMap);
       return resultModel;
   }
   /**
   * @Description: 实名认证编辑，只允许编辑证件号，证件类型，附件
   * @Author: zhengyunfei
   * @Date: 2019/3/8
   * @time:10:40
   */
   @PostMapping(value = "/update",produces = "application/json;charset=UTF-8")
   @ApiOperation(value = "实名认证编辑",notes = "实名认证(理财师发起)",position = 1,response = Object.class)
   public Object isShiMingRenZhengByMobile(IdCardBo idCardBo, HttpServletRequest request,String imagJson){
       ResultModel resultModel=new ResultModel();
       Map<String,Object> queryMap=new HashMap<>();
       System.out.println("imgJson=========="+imagJson);
       List<AppFileSimpleBo> imgList= JsonListUtil.jsonToList(imagJson,AppFileSimpleBo.class);
       List<AppFileSimpleBo> notDeleteImage=new ArrayList<>();
       //参数格式校验
       String userName=idCardBo.getUserName();
       String cardType=idCardBo.getCardType();//证件类型
       String cardNo=idCardBo.getCardNo();//证件号码
       String cCustNo=idCardBo.getcCustNo();
       if (shiMingRenZhengService.validParamMethod(resultModel,idCardBo)) return resultModel;
       Connection con = shiMingRenZhengService.getConnection();
       ShiMingRenZhengProcedure shiMingRenZhengProcedure=new ShiMingRenZhengProcedure();
       queryMap.put("cCustNo",cCustNo);
       XuLieHaoBao xuLieHaoBao= (XuLieHaoBao) shiMingRenZhengMapper.getPserilNo(queryMap);//序列号
       String pSerilNo="";
       if(!StringUtil.isNullOrEmpty(xuLieHaoBao)){
            pSerilNo=xuLieHaoBao.getlSerialNo();
       }
       System.out.println("pSerilNo=================="+pSerilNo);
       ShiMingRenZhengProcedureReturnInfo returnInfo=shiMingRenZhengProcedure.update(pSerilNo,idCardBo,con);

       if(cardType.equals("0")) {//只有是身份证的时候才调用实名认证接口
           SmrzBo result= SmrzUtils.getResult(userName,cardNo);
           if(!result.getStatus().equals("01")){
               System.out.println("实名认证返回结果====================="+result.getMsg());
               // resultModel.setMessage("姓名和身份证号不匹配");
               //resultModel.setCode(result.getStatus());
               resultModel.setMessage(ShiMingRenZhengStatus.SHI_MING_REN_ZHENG_STATUS_ERROR.getMessage());
               resultModel.setCode(ShiMingRenZhengStatus.SHI_MING_REN_ZHENG_STATUS_ERROR.getCode());
               //return true;
           }else{
               //param.setAreaAddress(result.getArea());
               //实名认证成功，同时更新实名认证的状态
               resultModel.setCode(ShiMingRenZhengStatus.SHI_MING_REN_ZHENG_STATUS_SUCCESS.getCode());
               resultModel.setMessage(ShiMingRenZhengStatus.SHI_MING_REN_ZHENG_STATUS_SUCCESS.getMessage());
           }
           shiMingRenZhengService.updateSmrzStatus(resultModel, cCustNo,userName);
       }
       String reasonCode=returnInfo.getpReasonCode();
       queryMap.put("smrzResult",returnInfo);
       boolean isDeleteFirstFlg=false;
       //处理附件
       for(int i=0;i<imgList.size();i++){
           boolean isDelete=imgList.get(i).isDelete();
           String cCatalog=imgList.get(i).getcCatalog();
           if("TCUSTREGISTERREQ_MAIN".equals(cCatalog)){
               isDeleteFirstFlg=imgList.get(i).isDelete();
           }
           if(isDelete){
               //删除app附件
               Map<String,Object> acceDtlMap=new HashMap<>();
               acceDtlMap.put("lStorageid",imgList.get(i).getlStorageId());
               //删除app附件
               crmAcceDtlMapper.deleteByMap(acceDtlMap);
               crmAcceDtlMapper.deleteOldTblobStorageFileByMap(acceDtlMap);
               //删除crm附件
               shiMingRenZhengFileMapper.deleteOldFileByMap(acceDtlMap);
           }else{
               notDeleteImage.add(imgList.get(i));
           }
       }
       //如果第一张被删除了，才处理实名认证第一张图片
       if(isDeleteFirstFlg){
           for(int i=0;i<notDeleteImage.size();i++){
               if(i==0){
                   AppFileBo appFileBo=new AppFileBo();
                   //将未删除的第一张变为首张
                   Map<String, Object> crmAcceDtlQueryMap=new HashMap<>();
                   String cSubkeyId=notDeleteImage.get(0).getcSubkeyId();
                   String oLstorageId=notDeleteImage.get(0).getlStorageId();
                   appFileBo.setcSubkeyId(cSubkeyId);
                   String lStrorageId=shiMingRenZhengUploadMapper.getLstrorageId(appFileBo);
                   crmAcceDtlQueryMap.put("lStorageid",lStrorageId);
                   CrmAcceDtlEntity crmAcceDtlEntity= (CrmAcceDtlEntity) crmAcceDtlMapper.get(crmAcceDtlQueryMap);
                   TblobstorageEntity tblobstorageEntity=crmAcceDtlMapper.getTblobstorage(crmAcceDtlQueryMap);
                   appFileBo.setlStorageid(oLstorageId);
                   appFileBo.setlStorageidFirst(lStrorageId);
                   appFileBo.setcCataLog("TCUSTREGISTERREQ_MAIN");
                   appFileBo.setFileUrl(notDeleteImage.get(i).getFileUrl());
                   if(!StringUtil.isNullOrEmpty(tblobstorageEntity)){
                       appFileBo.setUserId(tblobstorageEntity.getcCreator());
                       appFileBo.setcFileSize(tblobstorageEntity.getlFilesize());
                       appFileBo.setcFilename(tblobstorageEntity.getcFilename());
                   }
                   Map<String,Object> deptNodeCodeQuerMap=new HashMap<>();
                   String userId=appFileBo.getUserId();
                   if(StringUtil.isNullOrEmpty(userId)){
                       userId="";
                   }
                   deptNodeCodeQuerMap.put("userId",userId);
                   String deptNodeCode=shiMingRenZhengUploadMapper.getDeptNodeCode(deptNodeCodeQuerMap);
                   if(StringUtil.isNullOrEmpty(deptNodeCode)){
                       deptNodeCode="";
                   }
                   appFileBo.setDeptNodeCode(deptNodeCode);
                   //判断第一张的是否被删除，如果第一张的被删除了，则需要将现在的第一张变更为首张，否则不用管
                   shiMingRenZhengUploadMapper.updateFirst(appFileBo);
                   if(StringUtil.isNullOrEmpty(crmAcceDtlEntity)){
                       //保存文件附件到app数据库
                       CrmAcceDtlBo crmAcceDtlBo = new CrmAcceDtlBo();
                       crmAcceDtlBo.setLStorageid(lStrorageId);
                       crmAcceDtlBo.setFileUrl(appFileBo.getFileUrl());
                       crmAcceDtlMapper.add(crmAcceDtlBo);
                   }
            /*   else{
                   shiMingRenZhengUploadMapper.updateFirst(appFileBo);
               }*/
                   //保存文件到crm
                   tblobstorageEntity.setcNodecode(deptNodeCode);
                   tblobstorageEntity.setcFilename(crmAcceDtlEntity.getCFilename());
                   tblobstorageEntity.setlFilesize(tblobstorageEntity.getlFilesize());
                   tblobtSorageMapper.add(tblobstorageEntity);
                   //delete crm表
                   crmAcceDtlMapper.deleteByMap(crmAcceDtlQueryMap);
                   crmAcceDtlMapper.deleteOldTblobStorageFileByMap(crmAcceDtlQueryMap);
                   shiMingRenZhengFileMapper.deleteOldFileByMap(crmAcceDtlQueryMap);
               }
           }
       }

       if("1".equals(reasonCode)){
           //如果上述结果返回p_reasoncode = ‘1’并且附件信息有改动 则处理附件逻辑，先删除原来的附件
          /* Map<String,Object> deleteParam=new HashMap<>();
           deleteParam.put("cSubkeyId",pSerilNo);
           shiMingRenZhengFileMapper.deleteOldFile(deleteParam);*/
           resultModel.setData(returnInfo.getpReasonCode2());//返回实名认证对应附件输出编号
           resultModel.setCode(ResultStatus.SUCCESS.getCode());
           resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
       }else{
           resultModel.setCode(ResultStatus.ERROR.getCode());
           resultModel.setMessage(returnInfo.getpReasonInfo());
       }

       return resultModel;
   }
    /***获取crm附件列表**/
    @GetMapping("/getCrmFileList")
    @ApiOperation(value = "获取crm附件",notes = "获取crm附件",position = 1,response = Object.class)
    public Object getCrmFileList(String cCustNo){
        ResultModel resultModel=new ResultModel();
        Map<String,Object> resultMap=new HashMap<>();
        Map<String,Object> queryMap=new HashMap<>();
        queryMap.put("cCustNo",cCustNo);
        List<AppFileSimpleBo> fileList=shiMingRenZhengMapper.getSmrzCrmFile(queryMap);
        resultMap.put("resultFile",fileList);
        resultModel.setCode(ResultStatus.SUCCESS.getCode());
        resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
        resultModel.setData(resultMap);
        return resultModel;
    }
}
